using System;
using System.Drawing;
using System.Linq;
using MonoTouch.UIKit;
using Beauty;
namespace Beauty.Module.Pos
{
	public   class TopMenuCtrl:UIViewController
    {
        private const int TagOffset = 1000;
        private const float tabBarHeight = 60.0f;
		public static UIButton cmdHome;
		public static UIButton cmdShowType;
        private UIView tabButtonsContainerView;
		public static UIView contentContainerView;
        private UIImageView indicatorImageView;
        private UIViewController[] viewControllers;
        private int selectedIndex;
        private int initialSelectedIndex = -1;
		UILabel lbList;
		public string isNameSelected { get; set;}
        protected SidebarController SidebarController
        {
            get
            {
                return (UIApplication.SharedApplication.Delegate as AppDelegate).RootViewController.SidebarController;
            }
        }
        public TopMenuCtrl(int initialSelectedIndex)
        {
            this.initialSelectedIndex = initialSelectedIndex;
            
        }

        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            View.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight;

            var rect = new RectangleF(0.0f,20f, View.Bounds.Width , tabBarHeight);
            tabButtonsContainerView = new UIView(rect);

			cmdShowType = new UIButton (UIButtonType.Custom);
			cmdShowType.SetBackgroundImage (PosUtility.ImageFrom("Menu-list"), UIControlState.Normal);
			cmdShowType.SetBackgroundImage (PosUtility.ImageFrom("Menu-grid"), UIControlState.Selected);
			cmdShowType.Frame = new RectangleF (560, 20, tabBarHeight, tabBarHeight);
			cmdShowType.Layer.ZPosition = 1000;
			lbList = new UILabel (new RectangleF (0, 0, 50, 50));
			lbList.Text="List";
			lbList.TextColor = UIColor.White;
			cmdHome = new UIButton (UIButtonType.Custom);
			cmdHome.SetBackgroundImage (new UIImage ("mainmenu.png"), UIControlState.Normal);
			cmdHome.SetBackgroundImage (new UIImage ("mainmenu1.png"), UIControlState.Highlighted);
			cmdHome.Frame = new RectangleF (0, 20, tabBarHeight, tabBarHeight);
			cmdHome.Layer.ZPosition = 1000;
 			cmdHome.TouchUpInside += (object sender, EventArgs e) => {
                 SidebarController.ToggleMenu();
 				var swipeR = new UISwipeGestureRecognizer((rec) =>
 					{
 						if (selectedIndex < viewControllers.Length - 1)
 							SetSelectedIndex(selectedIndex + 1, true);
 					});
 				swipeR.Direction = UISwipeGestureRecognizerDirection.Left;
 				View.AddGestureRecognizer(swipeR);
 			};
            tabButtonsContainerView.BackgroundColor = UIColor.FromRGB(255, 71, 95);
            tabButtonsContainerView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth;
		
            Add(tabButtonsContainerView);
			Add(cmdHome);
			Add(cmdShowType);
			Add (lbList);
            rect.Y =20f+tabBarHeight;
            rect.Height = View.Bounds.Height - tabBarHeight;
            contentContainerView = new UIView(rect);
            contentContainerView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight;
            Add(contentContainerView);

            indicatorImageView = new UIImageView(PosUtility.ImageFrom("TabBarIndicator"));
            Add(indicatorImageView);

            ReloadTabButtons();

            SetSelectedIndex(initialSelectedIndex, false);

            var swipeLeft = new UISwipeGestureRecognizer((rec) =>
            {
                if (selectedIndex > 0)
                    SetSelectedIndex(selectedIndex - 1, true);
            });
            swipeLeft.Direction = UISwipeGestureRecognizerDirection.Right;
            View.AddGestureRecognizer(swipeLeft);

            var swipeRight = new UISwipeGestureRecognizer((rec) =>
            {
                if (selectedIndex < viewControllers.Length - 1)
                    SetSelectedIndex(selectedIndex + 1, true);
            });
            swipeRight.Direction = UISwipeGestureRecognizerDirection.Left;
            View.AddGestureRecognizer(swipeRight);
        }

        public override void ViewWillLayoutSubviews()
        {
            base.ViewWillLayoutSubviews();
            LayoutTabButtons();
        }
        
        public override bool ShouldAutorotate()
        {
            foreach (var viewController in viewControllers)
            {
                if (!viewController.ShouldAutorotate())
                    return false;
            }
            return true;
        }

        private void ReloadTabButtons()
        {
            RemoveTabButtons();
            AddTabButtons();

            // Force redraw of the previously active tab.
            int lastIndex = selectedIndex;
            selectedIndex = -1;
            selectedIndex = lastIndex;
        }

        private void AddTabButtons()
        {
			try {
				int index = 0;
				foreach (var viewController in viewControllers)
				{
					UIButton button = UIButton.FromType(UIButtonType.Custom);
					button.Tag = TagOffset + index;
				//	button.TitleLabel.Font = UIFont.SystemFontOfSize(18);
					//button.Layer.Position = new PointF (60, 30);
					// button.BackgroundColor = UIColor.FromRGB(255, 71, 95);

					UIOffset offset = viewController.TabBarItem.TitlePositionAdjustment;
					button.TitleEdgeInsets = new UIEdgeInsets(offset.Vertical, offset.Horizontal, 0.0f, 0.0f);
					button.ImageEdgeInsets = viewController.TabBarItem.ImageInsets;
					button.SetTitle(viewController.TabBarItem.Title, UIControlState.Normal);
					button.SetTitleColor(UIColor.White,UIControlState.Normal);
					button.SetImage(viewController.TabBarItem.Image, UIControlState.Normal);
				//	button.SetImage(viewController.TabBarItem.SelectedImage, UIControlState.Normal);
					 
					button.TouchDown += delegate
					{
						SetSelectedIndex(button.Tag - TagOffset, true);
					};

					deselectTabButton(button,viewController);
					tabButtonsContainerView.AddSubview(button);

					++index;
				}
			} catch {
				
			}
            
        }
        
        private void RemoveTabButtons()
        {
            while (tabButtonsContainerView.Subviews.Length > 0)
            {
                tabButtonsContainerView.Subviews[tabButtonsContainerView.Subviews.Length - 1].RemoveFromSuperview();
            }
        }

        private void LayoutTabButtons()
        {
            int index = 0;
            int count = viewControllers.Length;
			var rect = new RectangleF(20, 0, 120 , tabBarHeight);
         	 //  var rect = new RectangleF(20, 0, (float)Math.Floor(View.Bounds.Width / count) , tabBarHeight);
	 
            indicatorImageView.Hidden = true;

            var buttons = tabButtonsContainerView.Subviews;
            foreach (UIButton button in buttons)
            {
				if (index == count - 1) {
					rect.Width = View.Bounds.Width - rect.X;

					Console.WriteLine (rect.X);
					cmdShowType.Frame =new RectangleF(rect.X+80,23,30,30);
					lbList.Frame = new RectangleF(rect.X+82,35,50,50);
					lbList.Font = UIFont.SystemFontOfSize (16f);
					rect.X=rect.X + 120;
					rect.Width = rect.Width - 120;
				}

                button.Frame = rect;
                button.Font= UIFont.SystemFontOfSize (16f);
                rect.X += rect.Width;
				// button.Layer.BorderColor = UIColor.Black.CGColor;
				// button.Layer.BorderWidth = 1f;
                if (index == selectedIndex)
                    CenterIndicatorOnButton(button);

                ++index;
            }
        }
        
        private void CenterIndicatorOnButton(UIButton button)
        {
            var rect = indicatorImageView.Frame;
            rect.X = button.Center.X - (float)Math.Floor(indicatorImageView.Frame.Width / 2.0f);
            rect.Y = tabBarHeight - indicatorImageView.Frame.Height;
            indicatorImageView.Frame = rect;
            indicatorImageView.Hidden = false;
        }

        public void SetViewControllers(UIViewController[] newViewControllers)
        {
            if (newViewControllers.Length < 2)
                throw new Exception("MHTabBarController requires at least two view controllers");

            UIViewController oldSelectedViewController = selectedViewController;

            // Remove the old child view controllers.
            if (viewControllers != null)
            {
                foreach (var viewController in viewControllers)
                {
                    viewController.WillMoveToParentViewController(null);
                    viewController.RemoveFromParentViewController();
                }
            }

            viewControllers = newViewControllers.ToArray();

            // This follows the same rules as UITabBarController for trying to
            // re-select the previously selected view controller.
            int newIndex = Array.IndexOf(viewControllers, oldSelectedViewController);
            if (newIndex != -1)
                selectedIndex = newIndex;
            else if (newIndex < viewControllers.Length)
                selectedIndex = newIndex;
            else
                selectedIndex = 0;

            // Add the new child view controllers.
            foreach (var viewController in viewControllers)
            {
                AddChildViewController(viewController);
                viewController.DidMoveToParentViewController(this);
            }

            if (IsViewLoaded)
                ReloadTabButtons();
        }
        public void SetSelectedIndex(int newSelectedIndex, bool animated)
        {
            if (newSelectedIndex >= viewControllers.Length)
                throw new Exception("View controller index out of bounds");

            if (!IsViewLoaded)
            {
                selectedIndex = newSelectedIndex;
            }
            else if (selectedIndex != newSelectedIndex)
            {
                UIViewController fromViewController = null;
                UIViewController toViewController = null;

                if (selectedIndex != -1)
                {
                    UIButton fromButton = (UIButton)tabButtonsContainerView.ViewWithTag(TagOffset + selectedIndex);
					fromViewController = selectedViewController;
					deselectTabButton(fromButton,fromViewController);
                    
                }

                int oldSelectedIndex = selectedIndex;
                selectedIndex = newSelectedIndex;

                UIButton toButton = null;
                if (selectedIndex != -1)
                {
                    toButton = (UIButton)tabButtonsContainerView.ViewWithTag(TagOffset + selectedIndex);
					toViewController = selectedViewController;
					selectTabButton(toButton,toViewController);
                   
                }

                if (toViewController == null)  // don't animate
                {
                    fromViewController.View.RemoveFromSuperview();
                }
                else if (fromViewController == null)  // don't animate
                {
                    toViewController.View.Frame = contentContainerView.Bounds;
                    contentContainerView.AddSubview(toViewController.View);
                    CenterIndicatorOnButton(toButton);
                }
                else if (animated)
                {
                    var rect = contentContainerView.Bounds;
                    if (oldSelectedIndex < newSelectedIndex)
                        rect.X = rect.Width;
                    else
                        rect.X = -rect.Width;

                    toViewController.View.Frame = rect;
                    tabButtonsContainerView.UserInteractionEnabled = false;

                    this.Transition(
                        fromViewController, toViewController, 0.3f,
                        UIViewAnimationOptions.LayoutSubviews | UIViewAnimationOptions.CurveEaseOut,
                        delegate
                        {
                            var newRect = fromViewController.View.Frame;
                            if (oldSelectedIndex < newSelectedIndex)
                                newRect.X = -newRect.Width;
                            else
                                newRect.X = newRect.Width;

                            fromViewController.View.Frame = newRect;
                            toViewController.View.Frame = contentContainerView.Bounds;
                            CenterIndicatorOnButton(toButton);
                        },
                        delegate
                        {
                            tabButtonsContainerView.UserInteractionEnabled = true;
                        });
                }
                else  // not animated
                {
                    fromViewController.View.RemoveFromSuperview();

                    toViewController.View.Frame = contentContainerView.Bounds;
                    contentContainerView.AddSubview(toViewController.View);
                    CenterIndicatorOnButton(toButton);
                }
            }
        }
        private UIViewController selectedViewController
        {
            get
            {
                if (selectedIndex != -1 && viewControllers != null)
                    return viewControllers[selectedIndex];
                else
                    return null;
            }
        }
		private void selectTabButton(UIButton button,UIViewController selectedView)
        {  
            button.SetTitleColor(UIColor.White, UIControlState.Normal);
			button.SetImage(selectedView.TabBarItem.SelectedImage, UIControlState.Normal); 
			isNameSelected = selectedView.TabBarItem.Title;
        }
		private void deselectTabButton(UIButton button,UIViewController deselectView)
		{	if (deselectView.TabBarItem.Title != "Open Jobsheets") {
				button.SetTitleColor (UIColor.Black, UIControlState.Normal);
				button.SetImage (deselectView.TabBarItem.Image, UIControlState.Normal); 
			}
        }
    }
}